package org.springblade.gateway.filter;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * LogGatewayFilterFactory
 * 自定义
 *
 * @author yofi
 * @date 2021/4/15 17:19
 */
@Component
public class LogGatewayFilterFactory
	extends AbstractGatewayFilterFactory<LogGatewayFilterFactory.Config> {

	/**
	 * 构造函数
	 */
	public LogGatewayFilterFactory() {
		super(LogGatewayFilterFactory.Config.class);
	}

	/**
	 * 读取配置文件中的参数赋值到配置类中
	 * @return 配置参数
	 */
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("consoleLog","cacheLog");
	}

	/**
	 * 过滤器逻辑
	 * @param config 配置类
	 * @return 过滤链
	 */
	@Override
	public GatewayFilter apply(LogGatewayFilterFactory.Config config) {
		return new GatewayFilter() {
			@Override
			public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

				if (config.isCacheLog()) {
					System.out.println("cacheLog");
				}
				if (config.isConsoleLog()) {
					System.out.println("consoleLog");
				}
				return chain.filter(exchange);

			}
		};
	}

	/**
	 * 配置类 接受配置参数
	 */
	@Data
	@NoArgsConstructor
	public static class Config {

		private boolean consoleLog;
		private boolean cacheLog;

	}


}
